using System;
using System.Reflection;
using Rhizome.Contract;

namespace Rhizome.Model
{
    public sealed class EventTrigger : TriggerBase<object>
    {
        private readonly EventHandler _handler;
        private EventInfo _eventInfo;

        public EventTrigger()
        {
            _handler = Handler;
        }

        public string ClrEvent { get; set; }

        private EventInfo EventInfo
        {
            get { return _eventInfo ?? (_eventInfo = GetEventInfo()); }
        }

        private EventInfo GetEventInfo()
        {
            var plant = Plant;
            if (plant == null)
                throw new ValidationException("Plant can not be null");

            var type = plant.GetType();
            return type.GetEvent(ClrEvent);
        }

        private void Handler(object sender, EventArgs eventArgs)
        {
            Trigged();
        }

        public override void Initialize()
        {
            if (EventInfo == null)
                throw new ValidationException(string.Format("Event [{0}.{1}] not found", Plant.GetType(), ClrEvent));

            EventInfo.AddEventHandler(Plant, _handler);
        }

        public override void Cleanup()
        {
            if (_eventInfo != null)
                _eventInfo.RemoveEventHandler(Plant, _handler);
        }
    }
}